import { ref, computed } from 'vue'

export interface UseCounterOptions {
  initialValue?: number
  min?: number
  max?: number
  step?: number
}

export function useCounter(options: UseCounterOptions = {}) {
  const {
    initialValue = 0,
    min = Number.MIN_SAFE_INTEGER,
    max = Number.MAX_SAFE_INTEGER,
    step = 1,
  } = options

  const count = ref(initialValue)

  // 计算属性
  const isAtMin = computed(() => count.value <= min)
  const isAtMax = computed(() => count.value >= max)
  const percentage = computed(() => {
    if (max === Number.MAX_SAFE_INTEGER || min === Number.MIN_SAFE_INTEGER) {
      return 0
    }
    return ((count.value - min) / (max - min)) * 100
  })

  // 方法
  const increment = (amount = step) => {
    count.value = Math.min(count.value + amount, max)
  }

  const decrement = (amount = step) => {
    count.value = Math.max(count.value - amount, min)
  }

  const reset = () => {
    count.value = initialValue
  }

  const set = (value: number) => {
    count.value = Math.max(min, Math.min(max, value))
  }

  const toggle = (valueA: number = 0, valueB: number = 1) => {
    count.value = count.value === valueA ? valueB : valueA
  }

  return {
    count,
    isAtMin,
    isAtMax,
    percentage,
    increment,
    decrement,
    reset,
    set,
    toggle,
  }
}
